<template>
  <div class="page-container">
    <van-nav-bar 
      title="数据检控执行" 
      left-arrow 
      @click-left="router.back()"
    />

    <div class="content">
      <!-- 执行控制面板 -->
      <van-cell-group inset title="检控执行">
        <van-cell>
          <template #title>
            <div class="execution-controls">
              <van-button 
                type="primary" 
                size="large" 
                @click="executeAutoControl"
                :loading="autoControlLoading"
                block
              >
                自动检控
              </van-button>
              <div class="control-desc">执行所有已发布的检控规则</div>
            </div>
          </template>
        </van-cell>
        
        <van-cell>
          <template #title>
            <div class="execution-controls">
              <van-button 
                type="success" 
                size="large" 
                @click="showRuleSelector = true"
                :loading="manualControlLoading"
                block
              >
                常规检控
              </van-button>
              <div class="control-desc">选择指定规则进行检控</div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 执行历史 -->
      <van-cell-group inset title="执行历史">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <van-cell 
              v-for="log in executionLogs" 
              :key="log.id"
              :title="log.ruleName"
              :label="log.executionId"
              is-link
              @click="viewExecutionDetail(log)"
            >
              <template #extra>
                <div class="execution-info">
                  <van-tag :type="getExecutionStatusType(log.executionStatus)" size="small">
                    {{ log.executionStatusText }}
                  </van-tag>
                  <van-tag :type="getExecutionTypeType(log.executionType)" size="small" style="margin-top: 4px;">
                    {{ log.executionTypeText }}
                  </van-tag>
                </div>
              </template>
            </van-cell>
            
            <van-cell v-for="log in executionLogs" :key="'detail-' + log.id">
              <template #title>
                <div class="execution-detail">
                  <div>总记录数: {{ log.totalRecords }}</div>
                  <div>已检控: {{ log.checkedRecords }}</div>
                  <div>错误: {{ log.errorRecords }}</div>
                  <div>警告: {{ log.warningRecords }}</div>
                  <div>耗时: {{ log.durationText }}</div>
                  <div>开始时间: {{ formatDateTime(log.startTime) }}</div>
                </div>
              </template>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </van-cell-group>
    </div>

    <!-- 规则选择器 -->
    <van-popup v-model:show="showRuleSelector" position="bottom" style="height: 70%;">
      <div class="rule-selector">
        <div class="selector-header">
          <h3>选择检控规则</h3>
          <van-button type="primary" size="small" @click="executeManualControl">
            执行选中规则
          </van-button>
        </div>
        
        <div class="selector-content">
          <van-checkbox-group v-model="selectedRules">
            <van-cell-group>
              <van-cell 
                v-for="rule in availableRules" 
                :key="rule.id"
                clickable
                @click="toggleRule(rule.id)"
              >
                <template #title>
                  <div class="rule-item">
                    <van-checkbox :name="rule.id" />
                    <div class="rule-info">
                      <div class="rule-name">{{ rule.ruleName }}</div>
                      <div class="rule-code">{{ rule.ruleCode }}</div>
                      <div class="rule-group">{{ rule.groupName }}</div>
                    </div>
                  </div>
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>
        
        <div class="selector-footer">
          <van-button block @click="showRuleSelector = false">取消</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 执行详情弹窗 -->
    <van-popup v-model:show="showExecutionDetail" position="center" style="width: 90%; max-height: 70%;">
      <div class="execution-detail-popup" v-if="currentExecutionDetail">
        <div class="detail-header">
          <h3>执行详情</h3>
          <van-icon name="cross" @click="showExecutionDetail = false" />
        </div>
        
        <div class="detail-content">
          <van-cell-group>
            <van-cell title="执行ID" :value="currentExecutionDetail.executionId" />
            <van-cell title="规则名称" :value="currentExecutionDetail.ruleName" />
            <van-cell title="执行类型" :value="currentExecutionDetail.executionTypeText" />
            <van-cell title="执行状态" :value="currentExecutionDetail.executionStatusText" />
            <van-cell title="总记录数" :value="currentExecutionDetail.totalRecords" />
            <van-cell title="已检控" :value="currentExecutionDetail.checkedRecords" />
            <van-cell title="错误记录" :value="currentExecutionDetail.errorRecords" />
            <van-cell title="警告记录" :value="currentExecutionDetail.warningRecords" />
            <van-cell title="开始时间" :value="formatDateTime(currentExecutionDetail.startTime)" />
            <van-cell title="结束时间" :value="formatDateTime(currentExecutionDetail.endTime)" />
          </van-cell-group>
          
          <van-cell-group title="执行详情" v-if="currentExecutionDetail.executionDetails">
            <van-cell>
              <template #title>
                <pre class="execution-json">{{ formatExecutionDetails(currentExecutionDetail.executionDetails) }}</pre>
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { dataControlApi } from '@/api'

const router = useRouter()

// 响应式数据
const executionLogs = ref([])
const availableRules = ref([])
const selectedRules = ref([])
const currentExecutionDetail = ref(null)

const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const autoControlLoading = ref(false)
const manualControlLoading = ref(false)
const showRuleSelector = ref(false)
const showExecutionDetail = ref(false)

// 分页参数
const pageParams = reactive({
  pageNo: 1,
  pageSize: 10
})

// 加载执行历史
const loadExecutionHistory = async (reset = false) => {
  if (reset) {
    pageParams.pageNo = 1
    executionLogs.value = []
    finished.value = false
  }

  loading.value = true
  try {
    const params = {
      ...pageParams
    }
    
    const logs = await dataControlApi.getExecutionHistory(params)
    
    if (reset) {
      executionLogs.value = logs
    } else {
      executionLogs.value.push(...logs)
    }
    
    // 判断是否还有更多数据
    finished.value = logs.length < pageParams.pageSize
    
    if (!finished.value) {
      pageParams.pageNo++
    }
  } catch (error) {
    showToast('加载失败: ' + error.message)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 加载可用规则
const loadAvailableRules = async () => {
  try {
    const response = await dataControlApi.getRuleList({
      pageNo: 1,
      pageSize: 100,
      publishStatus: 'PUBLISHED'
    })
    availableRules.value = response.records
  } catch (error) {
    showToast('加载规则失败: ' + error.message)
  }
}

// 下拉刷新
const onRefresh = () => {
  loadExecutionHistory(true)
}

// 上拉加载
const onLoad = () => {
  if (!finished.value) {
    loadExecutionHistory()
  }
}

// 自动检控
const executeAutoControl = async () => {
  try {
    await showConfirmDialog({
      title: '确认执行',
      message: '确定要执行自动检控吗？这将执行所有已发布的规则。'
    })
    
    autoControlLoading.value = true
    const executionId = await dataControlApi.executeAutoControl()
    showToast(`自动检控已启动，执行ID: ${executionId}`)
    
    // 刷新执行历史
    setTimeout(() => {
      loadExecutionHistory(true)
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      showToast('启动失败: ' + error.message)
    }
  } finally {
    autoControlLoading.value = false
  }
}

// 常规检控
const executeManualControl = async () => {
  if (selectedRules.value.length === 0) {
    showToast('请选择要执行的规则')
    return
  }
  
  try {
    await showConfirmDialog({
      title: '确认执行',
      message: `确定要执行选中的 ${selectedRules.value.length} 个规则吗？`
    })
    
    manualControlLoading.value = true
    const executionId = await dataControlApi.executeManualControl(selectedRules.value)
    showToast(`常规检控已启动，执行ID: ${executionId}`)
    
    showRuleSelector.value = false
    selectedRules.value = []
    
    // 刷新执行历史
    setTimeout(() => {
      loadExecutionHistory(true)
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      showToast('启动失败: ' + error.message)
    }
  } finally {
    manualControlLoading.value = false
  }
}

// 切换规则选择
const toggleRule = (ruleId) => {
  const index = selectedRules.value.indexOf(ruleId)
  if (index > -1) {
    selectedRules.value.splice(index, 1)
  } else {
    selectedRules.value.push(ruleId)
  }
}

// 查看执行详情
const viewExecutionDetail = async (log) => {
  try {
    currentExecutionDetail.value = await dataControlApi.getExecutionDetail(log.executionId)
    showExecutionDetail.value = true
  } catch (error) {
    showToast('加载详情失败: ' + error.message)
  }
}

// 获取执行状态类型
const getExecutionStatusType = (status) => {
  const typeMap = {
    'RUNNING': 'primary',
    'SUCCESS': 'success',
    'FAILED': 'danger'
  }
  return typeMap[status] || 'default'
}

// 获取执行类型类型
const getExecutionTypeType = (type) => {
  const typeMap = {
    'AUTO': 'warning',
    'MANUAL': 'primary'
  }
  return typeMap[type] || 'default'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未完成'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化执行详情
const formatExecutionDetails = (details) => {
  try {
    if (typeof details === 'string') {
      return JSON.stringify(JSON.parse(details), null, 2)
    }
    return JSON.stringify(details, null, 2)
  } catch (error) {
    return details
  }
}

onMounted(() => {
  loadExecutionHistory(true)
  loadAvailableRules()
})
</script>

<style scoped>
.content {
  padding: 16px;
}

.execution-controls {
  width: 100%;
}

.control-desc {
  font-size: 12px;
  color: #969799;
  margin-top: 4px;
}

.execution-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.execution-detail {
  font-size: 12px;
  color: #969799;
  line-height: 1.5;
}

.execution-detail div {
  margin-bottom: 4px;
}

.rule-selector {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.selector-header {
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selector-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.selector-footer {
  padding: 16px;
  border-top: 1px solid #ebedf0;
}

.rule-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.rule-info {
  flex: 1;
}

.rule-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.rule-code {
  font-size: 12px;
  color: #969799;
  margin-bottom: 2px;
}

.rule-group {
  font-size: 12px;
  color: #1989fa;
}

.execution-detail-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-header {
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.execution-json {
  font-size: 12px;
  background: #f7f8fa;
  padding: 8px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
}

.van-cell-group {
  margin-bottom: 16px;
}
</style>
